﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using ThoiTrang.Entities;
using ThoiTrang.Business;
using System.Collections.Generic;

public partial class listing : System.Web.UI.Page
{
    #region Properties
    private int ContentLength = 0;

    protected int CatMainId
    {
        get
        {
            int id = 1;
            string str = Request[FOConstants.QSP_MCID];
            if (str != string.Empty && Convert.ToInt32(str) > 0)
            {
                id = Convert.ToInt32(str);
            }
            return id;
        }
    }

    protected int CatSubId
    {
        get
        {
            int id = 1;
            string str = Request[FOConstants.QSP_SCID];
            if (str != string.Empty && Convert.ToInt32(str) > 0)
            {
                id = Convert.ToInt32(str);
            }
            return id;
        }
    }

    protected int Paging
    {
        get
        {
            int id = 1;
            string str = Request[FOConstants.QSP_PAGING];
            if (str != string.Empty && Convert.ToInt32(str) > 0)
            {
                id = Convert.ToInt32(str);
            }
            return id;
        }
    }

    protected string search
    {
        get 
        {
            if (String.IsNullOrEmpty(Request[FOConstants.QSP_SEARCH]))
                return string.Empty;
            return Request[FOConstants.QSP_SEARCH];
        }
    }

    protected string FYear
    {
        get
        {
            if (String.IsNullOrEmpty(Request[FOConstants.QSP_FY]))
                return string.Empty;
            return Request[FOConstants.QSP_FY];
        }
    }

    protected string FSeason
    {
        get
        {
            if (String.IsNullOrEmpty(Request[FOConstants.QSP_FS]))
                return string.Empty;
            return Request[FOConstants.QSP_FS];
        }
    }
    #endregion

    #region Methods
    protected void Page_Load(object sender, EventArgs e)
    {       
        LoadGeneralData();
        SetActiveGroup();
        LoadOptions();
        if (!IsPostBack)
        {           
            SetStatPopularity();
            //TTHelper.UpdateSession(Request[FOConstants.QSP_CKID]);
        }
        LoadArticles();
        LoadMsg();
    }
    public void LoadMsg()
    {
        //msg=1
        //<strong>Mục này đả được lưu!</strong> Truy cập vào <a href=#>Tài khoản</a> để xem mục yêu thích của bạn.
        if (Request["msg"] != null)
        {
            msg.Visible = true;
            switch (Request["msg"])
            {
                case "1":
                    msg.InnerHtml = "<strong>Mục này đã được lưu!</strong> Truy cập vào <a href=user_index.aspx?t=t&amp;ckid=" + SessionManager.GetCookie() + ">Tài khoản</a> để xem mục yêu thích của bạn.";
                    break;
                default:
                    msg.Visible = false;
                    break;
            }
        }
    }

    protected override void OnInit(EventArgs e)
    {
        rptItems.ItemDataBound += new RepeaterItemEventHandler(rptItems_ItemDataBound);
        btnLimit.Click += new EventHandler(btnLimit_ServerClick);
    }

    protected void rptItems_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            List<a_Article> arts = e.Item.DataItem as List<a_Article>;
            UserControls_ArticleItem uc1 = e.Item.FindControl("art1") as UserControls_ArticleItem;
            UserControls_ArticleItem uc2 = e.Item.FindControl("art2") as UserControls_ArticleItem;
            UserControls_ArticleItem uc3 = e.Item.FindControl("art3") as UserControls_ArticleItem;

            if (arts.Count>0) uc1.SetValue(arts[0], ContentLength);
            if (arts.Count>1) uc2.SetValue(arts[1], ContentLength);
            if (arts.Count>2) uc3.SetValue(arts[2], ContentLength);
        }
    }

    protected void btnLimit_ServerClick(object sender, EventArgs e)
    {
        string link = "listing.aspx";
        link += String.Format("?{0}={1}", FOConstants.QSP_MCID, CatMainId);
        link += String.Format("&{0}={1}", FOConstants.QSP_SCID, CatSubId);
        link += String.Format("&{0}={1}", FOConstants.QSP_FS, ddlSeason.SelectedValue);
        link += String.Format("&{0}={1}", FOConstants.QSP_FY, ddlYear.SelectedValue);
        link += String.Format("&{0}={1}", FOConstants.QSP_SEARCH, "");
        link += String.Format("&{0}={1}", FOConstants.QSP_CKID, SessionManager.GetCookie());
        Response.Redirect(link);
    }

    protected void SetStatPopularity()
    {
        try
        {
            a_CatSub sub = a_CatSubService.Geta_CatSub(CatSubId);
            if (sub == null) return;
            sub.StatPopularity += 1;
            a_CatSubService.Updatea_CatSub(sub);
        }
        catch (Exception ex)
        {
        }
    }

    protected string GetCacheKey()
    {
        return string.Format("listing_{0}_{1}_{2}_{3}_{4}_{5}", CatMainId, CatSubId, search, FYear, FSeason, Paging);
    }

    protected void LoadArticles()
    {
        try
        {
            int total = 0;
            int index = 1;
            if (Request["cp"] != null) index = int.Parse(Request["cp"]);
            int pageSize = hplPager.PerPage;

            ArrayList arr = (ArrayList)Cache[GetCacheKey()];
            String strTotal = (String)Cache["total"];
            if (arr == null)
            {
                //List<a_Article> arts = a_ArticleService.Geta_ArticleListBySubIdAndMainId(CatMainId, CatSubId, a_ArticleColumns.ID, ThoiTrang.Data.OrderDirection.DESC, index, pageSize, out total);
                List<a_Article> arts = a_ArticleService.Geta_ArticleListByAll(CatMainId, CatSubId, "", FYear, FSeason, "", search, a_ArticleColumns.ID, ThoiTrang.Data.OrderDirection.DESC, index, pageSize, out total);
                int n = arts.Count - (arts.Count % 3);
                arr = new ArrayList();
                for (int i = 0; i < n; i += 3)
                {
                    arr.Add(arts.GetRange(i, 3));
                }
                if (arts.Count - n > 0) arr.Add(arts.GetRange(n, arts.Count - n));

                Cache.Insert(GetCacheKey(), arr, null, DateTime.Now.AddHours(8), TimeSpan.Zero);
                Cache.Insert("total", total.ToString(), null, DateTime.Now.AddHours(8), TimeSpan.Zero);
                strTotal = total.ToString();
            }
            ContentLength = FOConstants.MaxLength / pageSize;
           
            rptItems.DataSource = arr;
            rptItems.DataBind();
            hplPager.Total = int.Parse(strTotal);
        }
        catch (Exception ex)
        {
        }
    }    

    protected void SetActiveGroup()
    {
        try
        {
            a_CatMain main = a_CatMainService.Geta_CatMain(CatMainId);
            if (main == null) return;
            a_CatGroup group = a_CatGroupService.Geta_CatGroup(main.GroupID);
            if (group == null) return;
            menuLeft.GroupId = group.GroupID;
            footer.GroupId = group.GroupID;
            footer.SubId = CatSubId;
            footer.MainId = CatMainId;
            ((MasterPage)Master).ActivePage = group.GroupName;
        }
        catch (Exception ex)
        {
        }
    }

    protected void LoadGeneralData()
    {
        try
        {
            //Get Header Image
            a_CatSub sub = (a_CatSub)Cache[string.Concat("Header_", CatSubId.ToString())];
            if (sub == null)
            {
                sub = a_CatSubService.Geta_CatSub(CatSubId);
                Cache.Insert(string.Concat("Header_", CatSubId.ToString()), sub, null, DateTime.Now.AddHours(8), TimeSpan.Zero);
            }
            imgHeader.Src = TTHelper.GetHeaderImagePath(sub.Name);

            //Get page Title
            string key = string.Concat("Title_",CatMainId, "_", CatSubId);
            string strTemp = (string)Cache[key];
            if(strTemp==null)
            {
                a_SEO_Content sc = a_SEO_ContentService.Geta_SEO_ContentListByCatMainAndCatSub(int.Parse(Request["mcid"]), int.Parse(Request["scid"]));
                if (sc == null) return;
                strTemp = sc.Title.Replace("\"&strYearPrevious&\"", (DateTime.Now.Year - 1).ToString());
                strTemp = strTemp.Replace("\"&strYear&\"", " - " + DateTime.Now.Year.ToString());

                Cache.Insert(key, strTemp, null, DateTime.Now.AddHours(8), TimeSpan.Zero);
            }
            Page.Title = (strTemp!=null)?strTemp:"Thoitrang.com";
        }
        catch (Exception ex)
        {
        }
    }

    protected void LoadOptions()
    {
        if (Page.IsPostBack) return;
        ListItem item1 = new ListItem(DateTime.Now.Year.ToString(), DateTime.Now.Year.ToString());
        ListItem item2 = new ListItem((DateTime.Now.Year + 1).ToString(), (DateTime.Now.Year + 1).ToString());
        ddlYear.Items.Add(new ListItem("Xem Hết", ""));
        ddlYear.Items.Add(item1);
        ddlYear.Items.Add(item2);

        ddlSeason.Items.Add(new ListItem("Xem Hết", ""));
        ListItem item3 = new ListItem("Thu-Đông", "1");
        ListItem item4 = new ListItem("Xuân-Hè", "2");
        if (DateTime.Now.Month >= 1 && DateTime.Now.Month <= 5)
        {
            ddlSeason.Items.Add(item3);
            ddlSeason.Items.Add(item4);
        }
        else
        {
            ddlSeason.Items.Add(item4);
            ddlSeason.Items.Add(item3);
        }
    }

    protected string GetYearOptions()
    {
        string res = string.Empty;
        
        res += String.Format("\t\t\t\t\t\t\t\t\t\t<option value=\"{0}\">{0}</option>\n", DateTime.Now.Year.ToString());
        res += String.Format("\t\t\t\t\t\t\t\t\t\t<option value=\"{0}\">{0}</option>\n", (DateTime.Now.Year+1).ToString());
        return res;
    }

    protected string GetSeasonOptions()
    {
        string res = string.Empty;
        if (DateTime.Now.Month >= 1 && DateTime.Now.Month <= 5)
        {
            res += "\t\t\t\t\t\t\t\t\t\t<option value=\"1\">Thu-Đông</option>\n";
            res += "\t\t\t\t\t\t\t\t\t\t<option value=\"2\">Xuân-Hè</option>\n";
        }
        else
        {
            res += "\t\t\t\t\t\t\t\t\t\t<option value=\"1\">Xuân-Hè</option>\n";
            res += "\t\t\t\t\t\t\t\t\t\t<option value=\"2\">Thu-Đông</option>\n";
        }
        return res;
    }
    #endregion     


}
